<template>
    <div>
        <el-breadcrumb separator-class="el-icon-caret-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>


        <!--卡片视图-->
        <el-card class="box-card">

            <el-row :gutter="40">
                <el-col :span="9">
                    <!--搜素与添加区域-->
                    <el-input v-model="queryInfo.query" clearable @clear="getUserList" placeholder="请输入内容">
                        <i slot="suffix" class="el-input__icon el-icon-search" @click="getUserList(1)"></i>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" size="medium" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!--user数据-->
            <el-table border stripe :data="userList">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column
                        prop="role_name"
                        label="角色">
                </el-table-column>
                <el-table-column
                        prop="username"
                        label="姓名">
                </el-table-column>
                <el-table-column
                        prop="mobile"
                        label="电话">
                </el-table-column>
                <el-table-column
                        prop="email"
                        label="邮箱">
                </el-table-column>
                <el-table-column
                        label="状态">
                    <!--指定了scope就会覆盖上面的prop-->
                    <template slot-scope="scope">
                        <el-switch @change="userStateChange(scope.row)"
                                   v-model="scope.row.mg_state"
                                   active-color="#13ce66"
                                   inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" circle @click="showEditDialog(scope.row.id)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" circle @click="deleteUserById(scope.row.id)"></el-button>
                        <!--文字提示框-->
                        <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" circle @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="userTotal">
            </el-pagination>

        </el-card>

        <!--添加用户对话框-->
        <el-dialog
                title="添加用户"
                :visible.sync="dialogVisible"
                 width="50%"
                 @close="addDialogClose"   >
            <!--内容主体区-->
            <el-form :rules="addFormRules" :model="addForm" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
                 <el-button @click="dialogVisible = false">取 消</el-button>
                 <el-button type="primary" @click="addUer">确 定</el-button>
            </span>
        </el-dialog>

        <!--修改用户的对话框-->
        <el-dialog
                title="修改用户"
                :visible.sync="editDialogVisible"
                width="50%" @close="editDialogClose">
            <el-form :rules="editFormRoles" :model="editForm" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateUserInfo">确 定</el-button>
            </span>
        </el-dialog>

        <!--分配角色的对话框-->
        <el-dialog
                title="分配角色"
                :visible.sync="setRoleDialog"
                width="30%"
                @close="setRoleDialogClose">
            <div>
                <p>当前的用户：{{userInfo.username}}</p>
                <p>当前的角色：{{userInfo.role_name}}</p>
                <p>选择的角色
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option
                                v-for="item in roleList"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                 <el-button @click="setRoleDialog = false">取 消</el-button>
                 <el-button type="primary" @click="saveRoleConfirm">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "Users",
        data() {
            //邮箱校验规则
            let checkEmail = (rule,value,cb) => {
                //验证邮箱的正则表达式
                const regEmail = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
                if (regEmail.test(value)){
                    return cb()
                }
                cb(new Error('请输入合法的邮箱'))
            };
            //手机校验规则
            let checkMobile = (rule,value,cb) => {
                const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
                if (regMobile.test(value)){
                    return cb();
                }
                cb(new Error('请输入合法的手机号'))
            };
            return {
                //请求查询对象
                queryInfo: {
                    query: '',
                    pagenum: 1,
                    pagesize: 2
                },

                //用户列表
                userList: [],
                userTotal: 0,
                dialogVisible: false,

                //添加用户的表单数据
                addForm: {},
                //添加用户的验证规则数据
                addFormRules: {
                    username: [
                        {required: true, message: '请输入账号', trigger: 'blur'},
                        {min: 3, max: 10, message: '用户名的长度在3-10个字符之间', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 15, message: '密码的长度在3-10个字符之间', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ]
                },

                //定义修改用户这个对话框默认为不显示
                editDialogVisible: false,

                //定义查询到的用户信息保存
                editForm: {},

                editFormRoles: {
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ]
                },

                //定义角色的对话框的显示
                setRoleDialog: false,

                //定义的用户的信息
                userInfo: {},

                //所有角色的数据列表
                roleList: [],

                //选中的角色信息
                selectedRoleId: '',

            }
        },
        created() {
            //发起请求来获取数据
            this.getUserList();
        },
        methods: {
            async getUserList(page = this.queryInfo.pagenum) {
                this.queryInfo.pagenum = page;
                const {data} = await this.$http.get('users', {params: this.queryInfo});
                console.log(data);
                if (data.meta.status !== 200) return this.$message.error("获取用户列表失败");
                this.userList = data.data.users;
                this.userTotal = data.data.total;
            },

            //监听pageSize改变的时间
            handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize;
                this.getUserList();
            },

            //页码值发送改变的时间
            handleCurrentChange(newPage) {
                this.queryInfo.pagenum = newPage;
                this.getUserList();
            },

            //监听开关状态的改变
            async userStateChange(userInfo) {
                const {data} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
                if (data.meta.status !== 200) {
                    userInfo.mg_state = !userInfo.mg_state;
                    return this.$message.error("更新用户状态失败");
                }
                this.$message.success("更新成功");
            },

            //监听对话框关闭事件，重置表单
            addDialogClose(){
                this.$refs.addFormRef.resetFields();
            },

            //添加新用户
            addUer(){
                this.$refs.addFormRef.validate(async valid => {
                    if(valid){
                        const {data} = await this.$http.post('users',this.addForm);
                        if (data.meta.status !== 201) return this.$message.error('添加用户失败');
                        this.$message.success('添加用户成功');
                        this.dialogVisible = false;
                        this.getUserList();
                    }
                })
            },

            //展示编辑用户的对话框
            async showEditDialog(id){
                this.editDialogVisible = true;
                const {data} = await this.$http.get(`users/${id}`);
                if (data.meta.status !== 200) return this.$message.error('获取用户信息失败');
                this.editForm = data.data;
            },


            //发送请求更新用户的信息
            updateUserInfo(){
                this.$refs.editFormRef.validate(async valid => {
                    if (valid){
                        const {data} = await this.$http.put(`users/${this.editForm.id}`,this.editForm);
                        if (data.meta.status !== 200) return this.$message.error('更新用户信息失败');
                        this.$message.success('更新用户成功');
                        this.editDialogVisible = false;
                        this.getUserList();
                    }
                })
            },

            //监听修改用户对话框的修改事件
            editDialogClose(){
                this.$refs.editFormRef.resetFields()
            },


            //根据Id删除对应的User
            async deleteUserById(id){
                //提示是否删除用户
               const result = await this.$confirm('是否永久删除该用户','提示',{
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => error);
                //确认删除则为字符串'confirm'，取消为'cancel'
               if (result !== 'confirm') return this.$message.info('已经取消了删除');

               const {data} = await this.$http.delete(`users/${id}`);
               if (data.meta.status !== 200) return this.$message.error('删除用户失败');
               //JS中的除法不会自动取整数
               this.$message.success('删除成功');
               const flag = this.queryInfo.pagenum === Math.floor(this.userTotal/this.queryInfo.pagesize) + 1 && this.userTotal % this.queryInfo.pagesize === 1;
               if (flag){
                   this.getUserList(this.queryInfo.pagenum - 1);
               }
               this.getUserList();
            },

            //设置角色按钮点击
            async setRole(userInfo){
                this.userInfo = userInfo;
                //还需要获取角色的列表
                const {data} = await this.$http.get('roles');
                if (data.meta.status !== 200)  return this.$message.error('获取角色列表失败');
                this.roleList = data.data;
                this.setRoleDialog = true;
            },

            //对话框确认点击分配角色
            async saveRoleConfirm(){
                if (!this.selectedRoleId)return this.$message.warning('请选择要分配的角色');
                const {data} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid: this.selectedRoleId});
                if (data.meta.status !== 200)  return this.$message.error(data.meta.msg);
                this.$message.success('更新角色成功');
                this.getUserList();
                this.setRoleDialog = false;
            },

            //监听分配角色对话框的关闭事件
            setRoleDialogClose(){
                this.selectedRoleId = '';
                this.userInfo = {};
            }
        }
    }
</script>

<style scoped lang="less">
    .el-pagination {
        margin-top: 15px;
    }
</style>
